package com.jeffse.light.stream.core.handler.encoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class DataStreamEncode extends MessageToByteEncoder<Object> {

    public DataStreamEncode(){
        super();
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object dataStream, ByteBuf byteBuf) throws Exception {
        byte[] body = convertToBytes(dataStream);
        int dataLength = body.length;  //读取消息的长度
        byteBuf.writeInt(dataLength);  //先将消息长度写入，也就是消息头
        byteBuf.writeBytes(body);  //消息体中包含我们要发送的数据
    }

    private byte[] convertToBytes(Object object) throws IOException {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream output = null;
        try {
            bos = new ByteArrayOutputStream();
            output = new ObjectOutputStream(bos);
            output.writeObject(object);
            output.flush();

            return bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            bos.close();
            output.close();
        }
        return null;
    }
}
